import Client from "./common";
import router from '../../router';
const dataURLtoFile =(dataurl, filename) => {//将base64转换为文件
  let  arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
  bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
  return new File([u8arr], filename, {type:mime});
}
const setToken = (token, user) => {
  let newTime = (new Date().getTime()); // 当前时间
  let expTime = 1000 * 60 * 60 * 1.8;
  let endTime = newTime + expTime;
  let tokenObj = {
    token: token,
    user: user,
    time: endTime
  };
  Client.setStore("CMSToken", tokenObj);
}
const delToken = () => {
  Client.removeStore("CMSToken");
}

const routeExpire =() => {
  router.beforeEach( (to, from, next) => {
    let obj,expireTime,currentTime,isExpire;
    obj = Client.getStore("CMSToken");
    if(obj){
      expireTime = obj.time;
      currentTime = (new Date()).getTime();
      isExpire = expireTime - currentTime;
      if(isExpire<=0){
        Client.removeStore("CMSToken");
        next('/login');
      }else if(to.fullPath != "/login") {
        next();
      }else{
        next('/');
      }
    }else{
      if(to.fullPath != "/login"){
        next('/login');
      }else{
        next();
      }
    }
  })
}

const Utils = {
  dataURLtoFile,
  routeExpire,
  setToken,
  delToken
}
export default Utils